package myTest;

import com.bjsxt.height.concurrent018.MyRejected;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试线程池
 *
 * Created by 杨志远 on 2017/5/29
 * email faryangsh@163.com.
 */
public class TestThreadPool {
    public static AtomicInteger num = new AtomicInteger(1);
    public volatile static boolean flag = true;
    public static String lock = new String("lock");
    //有界队列
//    public static BlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(10);

    //无界队列
    public static BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();


    public static void main(String[] args) {
//        testFixedThreadPool();
        testDefineThreadPool();
    }

    private static void testDefineThreadPool() {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 60,
                TimeUnit.SECONDS,
                queue,        //指定一种队列
                new MyRejected()
        );
        for (int i = 1; i <= 1000; i++) {
            threadPoolExecutor.execute(getRunnable());
        }

        threadPoolExecutor.shutdown();

    }

    private static void testFixedThreadPool() {
        ExecutorService executorService = Executors.newFixedThreadPool(30);
        List<Runnable> runs = new ArrayList<>();
        for (int i = 1; i <= 30; i++) {
            executorService.execute(getRunnable());
        }

    }

    private static Runnable getRunnable() {
        return () -> {
            while (flag) {
                synchronized (lock) {
                    if (num.get() == 1000) {
                        flag = false;
                    }
                    if (num.get()<1001){
                        System.out.println("num:" + num.getAndIncrement());
                    }
                }
                System.out.println("queue'size:"+queue.size());

                try {
                    Thread.currentThread().sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

//                System.out.println(Thread.currentThread().getName());
//                System.out.println(flag);
            }

        };
    }
}
